import React, {useEffect, useState} from 'react'
import {Card, Form, Button, Input, Select, Table, Row, Col, message} from 'antd'
import {SearchOutlined} from "@ant-design/icons"
import {
  getHosListRequest,
  getHosStatusRequest,
  getProvinceRequest,
  getCityOrDistrictListRequest,
  getHosTypeRequest
} from "@api/hospital/hospitalList"
import type {
  getHosListSearchParamsType,
  hospitalListItemsType,
  hospitalListContentType,
  getProvinceReturnType,
} from "@api/hospital/model/hospitalListTypes"
import {useNavigate} from "react-router-dom";


export default function HospitalList() {
  const [form] = Form.useForm()
  const navigate = useNavigate()
  //1.集中管理数据状态
  //设置加载中状态
  const [isLoading, setIsLoading] = useState(false)
  //设置页码状态
  const [page, setPage] = useState(1)
  //设置每页展示的数量的状态
  const [limit, setLimit] = useState(3)
  //设置传入的参数的状态
  const [searchParams, setSearchParams] = useState<getHosListSearchParamsType>({})
  //控制表格的数据
  const [hosListData, setHosListData] = useState<hospitalListContentType>([])
  //设置医院总数
  const [total, setTotal] = useState(0)
  //创建控制省列表数据状态
  const [province, setProvince] = useState<getProvinceReturnType>([])
  //创建控制获取省数据时获取市的列表数据状态
  const [city, setCity] = useState<getProvinceReturnType>([])
  //创建控制获取市数据时获取县的列表数据状态
  const [district, setDistrict] = useState<getProvinceReturnType>([])
  //控制医院等级的状态
  const [hosType, setHosType] = useState<getProvinceReturnType>([])

  //全局封装数据请求页面渲染函数
  const getHosList = async () => {
    const re = await getHosListRequest(page, limit, searchParams)
    // console.log('re', re)
    setHosListData(re.content)
    setTotal(re.totalElements)
    setIsLoading(false)
  }

  //1.页面加载初始就执行医院列表数据请求
  useEffect(() => {
    //  1.设置loading
    setIsLoading(true)

    getHosList()
  }, [page, limit, searchParams])

  //页面加载初始就执行获取省列表数据请求
  useEffect(() => {
    const getProvince = async () => {
      const re = await getProvinceRequest()
      // console.log('省列表数据', re)
      setProvince(re)
    }
    getProvince()
  }, [])
  //获取医院等级请求
  useEffect(() => {
    const getHosType = async () => {
      const re = await getHosTypeRequest()
      // console.log(re)
      setHosType(re)
    }
    getHosType()
  }, [])
  //2.集合回调函数位置
  //页面变化回调函数
  const pageChange = (current: number, pageSize: number) => {
    setPage(current)
    setLimit(pageSize)
  }
  //医院状态回调函数
  const changeStatusHandle = (id: string, status: 0 | 1) => {

    return async () => {
      await getHosStatusRequest(id, status)
      message.success('医院状态修改成功')
      getHosList()
    }

  }
  //在省数据变化时获取市的信息
  const changeProvinceHandle = async (value: string) => {
    const re = await getCityOrDistrictListRequest(value)
    // console.log(value,b,c)
    // console.log('市列表',re)
    setCity(re)
    form.setFieldsValue({cityCode: null, districtCode: null, hostype: null, status: null})
    setDistrict([])
  }
  //在市数据变化时获取县的信息
  const changeCityHandle = async (value: string) => {
    const re = await getCityOrDistrictListRequest(value)
    setDistrict(re)
    form.setFieldsValue({districtCode: null, hostype: null, status: null})
  }
  //收集表单数据
  const finishedHandle = (searchParams: getHosListSearchParamsType) => {

    setSearchParams(searchParams)
    // console.log('searchParams',searchParams)

  }
  //设置点击清楚的时候重置列表
  const clearSearch = () => {
    setSearchParams({})
    setCity([])
    setDistrict([])
  }

  const columns = [
    {
      title: '序号',
      width: 60,
      dataIndex: 'index',
      align: 'center' as 'center',
      render(_: any, __: any, index: number) {
        return index + 1
      }
    },
    {
      title: '医院logo',
      dataIndex: 'logoData',
      align: 'center' as 'center',
      render(logoData: string) {
        return <img width={100} src={`data:image/jpeg;base64,${logoData}`} alt=""/>
      }
    },
    {
      title: '医院名称',
      align: 'center' as 'center',
      dataIndex: 'hosname',
    },
    {
      title: '等级',
      align: 'center' as 'center',
      render(_: any, data: hospitalListItemsType) {
        return data.param.hostypeString
      }
    },
    {
      title: '详细地址',
      align: 'center' as 'center',
      render(_: any, data: hospitalListItemsType) {
        return data.param.fullAddress
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      align: 'center' as 'center',
      render(status: 0 | 1) {
        return status === 0 ? '下线' : '上线'
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      align: 'center' as 'center',
    },
    {
      title: '操作',
      width: 260,
      fixed: "right" as "right",
      dataIndex: "do",
      align: 'center' as 'center',
      render(_: any, data: hospitalListItemsType) {
        const {id,hoscode} = data
        return (
          <div>
            <Button
              type='primary'
              style={{marginRight: 10}}
              onClick={() => {
                navigate(`/syt/hospital/hospitalShow/${id}`)
              }}
            >查看</Button>
            <Button
              type='primary'
              style={{marginRight: 10}}
              onClick={()=>{
                navigate(`/syt/hospital/hospitalSchedule/${hoscode}`)
              }}
            >排班</Button>
            {
              data.status === 0 ?
                <Button
                  type='primary'
                  onClick={changeStatusHandle(data.id, 1)}
                >上线</Button> :
                <Button
                  type='primary'
                  onClick={changeStatusHandle(data.id, 0)}
                  style={{width: 70}}
                >下线</Button>
            }
          </div>
        )
      }
    }
  ];
  return (
    <div>
      <Card>
        <Form
          name="basic"
          form={form}
          onFinish={finishedHandle}
        >
          <Row justify="space-between">
            <Col span={5}>
              <Form.Item
                name="provinceCode"
              >
                <Select
                  placeholder="请输入省份"
                  allowClear
                  onChange={changeProvinceHandle}
                >
                  {
                    province.map(item => {
                      return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item
                name="cityCode"
              >
                <Select
                  placeholder="请输入市"
                  allowClear
                  onChange={changeCityHandle}
                >
                  {
                    city.map(item => {
                      return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item
                name="districtCode"
              >
                <Select
                  placeholder="请输入县/区"
                  allowClear
                >
                  {
                    district.map(item => {
                      return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col span={4}>
              <Form.Item
                name="hostype"
              >
                <Select
                  placeholder="医院类型"
                  allowClear
                >
                  {
                    hosType.map(item => {
                      return <Select.Option value={item.value} key={item.id}>{item.name}</Select.Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
            <Col span={2}>
              <Form.Item
                name="status"
              >
                <Select
                  placeholder="状态"
                  allowClear
                >
                  <Select.Option value={1}>上线</Select.Option>
                  <Select.Option value={0}>下线</Select.Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>


          <Row gutter={10}>
            <Col span={5}>
              <Form.Item
                name="hosname"
              >
                <Input placeholder="医院名称"/>
              </Form.Item>
            </Col>
            <Col span={5}>
              <Form.Item
                name="hoscode"
              >
                <Input placeholder='医院编号'/>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item wrapperCol={{offset: 8, span: 16}}>
                <Button type="primary" htmlType="submit" icon={<SearchOutlined/>}>
                  查询
                </Button>
              </Form.Item>
            </Col>
            <Col span={3}>
              <Form.Item wrapperCol={{offset: 8, span: 16}}>
                <Button type="default" htmlType="reset" onClick={clearSearch}>
                  清空
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>


        <Table
          style={{marginTop: "30px"}}
          columns={columns}
          dataSource={hosListData}
          scroll={{x: 1100}}
          bordered
          //在table中 要求dataSource中有key属性,但是如果真的没有key 则可以使用rowKey属性指定dataSource中的一个属性作为Key
          rowKey="id"
          loading={isLoading}

          pagination={{
            //页码的配置：当前页码
            current: page,
            //总数据的数量
            total,
            //每页条数
            pageSize: limit,
            //展示更改每页条数的选项(默认total大于50条的时候开启)
            pageSizeOptions: [3, 8, 15],
            //是否直接开启更新每页条数的选项
            showSizeChanger: true,

            showTotal(total) {
              return `总共有${total}条数据`
            },
            onChange: pageChange
          }}
        />
      </Card>
    </div>
  )
}
